package com.ruoyi.imports.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.imports.domain.*;
import com.ruoyi.imports.mapper.TdOperatingParamsMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.imports.mapper.TdOperatingParamsTypeMapper;
import com.ruoyi.imports.service.ITdOperatingParamsTypeService;

/**
 * 工艺参数类型Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-14
 */
@Service
public class TdOperatingParamsTypeServiceImpl implements ITdOperatingParamsTypeService {
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy年M月d日", Locale.CHINESE);

    static {
        DATE_FORMAT.setLenient(false); // 严格校验日期格式
    }
    @Autowired
    private TdOperatingParamsTypeMapper tdOperatingParamsTypeMapper;

    @Autowired
    private TdOperatingParamsMapper tdOperatingParamsMapper;

    /**
     * 查询工艺参数类型
     *
     * @param id 工艺参数类型主键
     * @return 工艺参数类型
     */
    @Override
    public TdOperatingParamsType selectTdOperatingParamsTypeById(Long id) {
        return tdOperatingParamsTypeMapper.selectTdOperatingParamsTypeById(id);
    }

    /**
     * 查询工艺参数类型列表
     *
     * @param tdOperatingParamsType 工艺参数类型
     * @return 工艺参数类型
     */
    @Override
    public List<TdOperatingParamsType> selectTdOperatingParamsTypeList(TdOperatingParamsType tdOperatingParamsType) {
        return tdOperatingParamsTypeMapper.selectTdOperatingParamsTypeList(tdOperatingParamsType);
    }

    /**
     * 新增工艺参数类型
     *
     * @param tdOperatingParamsType 工艺参数类型
     * @return 结果
     */
    @Override
    public int insertTdOperatingParamsType(TdOperatingParamsType tdOperatingParamsType) {
        tdOperatingParamsType.setCreateTime(DateUtils.getNowDate());
        return tdOperatingParamsTypeMapper.insertTdOperatingParamsType(tdOperatingParamsType);
    }

    /**
     * 修改工艺参数类型
     *
     * @param tdOperatingParamsType 工艺参数类型
     * @return 结果
     */
    @Override
    public int updateTdOperatingParamsType(TdOperatingParamsType tdOperatingParamsType) {
        tdOperatingParamsType.setUpdateTime(DateUtils.getNowDate());
        return tdOperatingParamsTypeMapper.updateTdOperatingParamsType(tdOperatingParamsType);
    }

    /**
     * 批量删除工艺参数类型
     *
     * @param ids 需要删除的工艺参数类型主键
     * @return 结果
     */
    @Override
    public int deleteTdOperatingParamsTypeByIds(Long[] ids) {
        return tdOperatingParamsTypeMapper.deleteTdOperatingParamsTypeByIds(ids);
    }

    /**
     * 删除工艺参数类型信息
     *
     * @param id 工艺参数类型主键
     * @return 结果
     */
    @Override
    public int deleteTdOperatingParamsTypeById(Long id) {
        return tdOperatingParamsTypeMapper.deleteTdOperatingParamsTypeById(id);
    }

    @Override
    public void importOperatingDataType(List<OperatingExcelData> excelDataList, Long projectId) {
        // 1. 基础校验
        if (excelDataList == null || excelDataList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }
        // 2. 日期连续性校验（核心逻辑）
        validateDateContinuity(excelDataList);
        // 存储Excel行索引与主表ID的映射（用于关联子表）
        HashMap<Integer, Long> operatingToMainMap = new HashMap<>(excelDataList.size());
        try {
            //处理主表
            for (int i = 0; i < excelDataList.size(); i++) {
                OperatingExcelData operatingExcelData = excelDataList.get(i);
                TdOperatingParams tdOperatingParams = buildMainData(operatingExcelData, projectId);
                tdOperatingParamsMapper.insertTdOperatingParams(tdOperatingParams);
                operatingToMainMap.put(i, tdOperatingParams.getId());
            }

            List<TdOperatingParamsType> typeDataList = new ArrayList<>();
            for (int i = 0; i < excelDataList.size(); i++) {
                OperatingExcelData operatingExcelData = excelDataList.get(i);
                Long mainId = operatingToMainMap.get(i);
                typeDataList.add(buildTypeData(operatingExcelData, mainId, "流量"));
                typeDataList.add(buildTypeData(operatingExcelData, mainId, "温度"));
                typeDataList.add(buildTypeData(operatingExcelData, mainId, "溶解氧"));
                typeDataList.add(buildTypeData(operatingExcelData, mainId, "污泥浓度"));
                typeDataList.add(buildTypeData(operatingExcelData, mainId, "污泥沉降比SV30"));
                typeDataList.add(buildTypeData(operatingExcelData, mainId, "剩余污泥量排放量"));

            }
            // 批量插入子表
            if (!typeDataList.isEmpty()) {
                tdOperatingParamsTypeMapper.batchInsert(typeDataList);
            }
        } catch (Exception e) {
            // 异常捕获与日志
            throw new RuntimeException("导入失败：" + e.getMessage(), e);
        }
    }

    private TdOperatingParamsType buildTypeData(OperatingExcelData operatingExcelData, Long mainId, String type) {
        TdOperatingParamsType typeData = new TdOperatingParamsType();
        typeData.setOperatinParamsId(mainId);
        typeData.setType(type);

        // 设置通用字段
        Long userId = SecurityUtils.getUserId();
        typeData.setCreateUser(userId);
        typeData.setUpdateUser(userId);
        typeData.setCreateTime(new Date());
        typeData.setUpdateTime(new Date());
        typeData.setIsDeleted(0);

        if ("流量".equals(type)) {
            typeData.setSurplusAmmoniaWater(operatingExcelData.getShengYuAnShui());
            typeData.setSteamedAmmoniaWastewater(operatingExcelData.getZhengAnFeiShui());
            typeData.setOtherWastewater(operatingExcelData.getQiTaFeiShui());
            typeData.setDilutionWater(operatingExcelData.getXiShiShui());
            typeData.setBiochemicalWaterA(operatingExcelData.getLiuLiangShengHuaA());
            typeData.setBiochemicalWaterB(operatingExcelData.getLiuLiangShengHuaB());
            typeData.setNitrationRefluxOneA(operatingExcelData.getLiuLiangYiJiXiaoHuaA());
            typeData.setNitrationRefluxOneB(operatingExcelData.getLiuLiangYiJiXiaoHuaB());
            typeData.setSludgeReturnOneA(operatingExcelData.getLiuLiangYiJiWuNiA());
            typeData.setSludgeReturnOneB(operatingExcelData.getLiuLiangYiJiWuNiB());
            typeData.setSludgeReturnTwoA(operatingExcelData.getLiuLiangErJiWuNiA());
            typeData.setSludgeReturnTwoB(operatingExcelData.getLiuLiangErJiWuNiB());
            typeData.setFinalEffluent(operatingExcelData.getLiuLiangZuiZhong());
        } else if ("温度".equals(type)) {
            typeData.setRegulatingPool(operatingExcelData.getWenDuTiaoJieChi());
            typeData.setPreExposure(operatingExcelData.getWenDuYuBaoChi());
            typeData.setPrimarySettlingTank(operatingExcelData.getWenDuChuChenChi());
            typeData.setAnaerobicTankA(operatingExcelData.getWenDuYanYangA());
            typeData.setAnaerobicTankB(operatingExcelData.getWenDuYanYangB());
            typeData.setAnoxicTankOneA(operatingExcelData.getWenDuYiJiQueYangA());
            typeData.setAnoxicTankOneB(operatingExcelData.getWenDuYiJiQueYangB());
            typeData.setAerobicTankOneA(operatingExcelData.getWenDuYiJiHaoYangA());
            typeData.setAerobicTankOneB(operatingExcelData.getWenDuYiJiHaoYangB());
            typeData.setAnoxicTankTwoA(operatingExcelData.getWenDuErJiQueYangA());
            typeData.setAnoxicTankTwoB(operatingExcelData.getWenDuErJiQueYangB());
            typeData.setAnoxicTankTwoA(operatingExcelData.getWenDuErJiHaoYangA());
            typeData.setAnoxicTankTwoB(operatingExcelData.getWenDuErJiHaoYangB());
        } else if ("溶解氧".equals(type)) {
            typeData.setAnoxicTankOneA(operatingExcelData.getRongJieYiJiQueYangA());
            typeData.setAnoxicTankOneB(operatingExcelData.getRongJieYiJiQueYangB());
            typeData.setAerobicTankOneA(operatingExcelData.getRongJieYiJiHaoYangA());
            typeData.setAerobicTankOneB(operatingExcelData.getRongJieYiJiHaoYangB());
            typeData.setAnoxicTankTwoA(operatingExcelData.getRongJieErJiQueYangA());
            typeData.setAnoxicTankTwoB(operatingExcelData.getRongJieErJiQueYangB());
            typeData.setAnoxicTankTwoA(operatingExcelData.getRongJieErJiHaoYangA());
            typeData.setAnoxicTankTwoB(operatingExcelData.getRongJieErJiHaoYangB());
        } else if ("污泥浓度".equals(type)) {
            typeData.setAerobicTankOneA(operatingExcelData.getWuNiYiJiHaoYangA());
            typeData.setAerobicTankOneB(operatingExcelData.getWuNiYiJiHaoYangB());
            typeData.setSludgeReturnOneA(operatingExcelData.getWuNiYiJiHuiLiuA());
            typeData.setSludgeReturnOneB(operatingExcelData.getWuNiYiJiHuiLiuB());
            typeData.setAnoxicTankTwoA(operatingExcelData.getWuNiErJiHaoYangA());
            typeData.setAnoxicTankTwoB(operatingExcelData.getWuNiErJiHaoYangB());
            typeData.setSludgeReturnTwoA(operatingExcelData.getWuNiErJiHuiLiuA());
            typeData.setSludgeReturnTwoA(operatingExcelData.getWuNiErJiHuiLiuB());
        } else if ("污泥沉降比SV30".equals(type)) {
            typeData.setAerobicTankOneA(operatingExcelData.getWuNiJiangChenYiJiHaoYangA());
            typeData.setAerobicTankOneB(operatingExcelData.getWuNiJiangChenYiJiHaoYangB());
            typeData.setSludgeReturnOneA(operatingExcelData.getWuNiJiangChenYiJiHuiLiuA());
            typeData.setSludgeReturnOneB(operatingExcelData.getWuNiJiangChenYiJiHuiLiuB());
            typeData.setAnoxicTankTwoA(operatingExcelData.getWuNiJiangChenErJiHaoYangA());
            typeData.setAnoxicTankTwoB(operatingExcelData.getWuNiJiangChenErJiHaoYangB());
            typeData.setSludgeReturnTwoA(operatingExcelData.getWuNiJiangChenErJiHuiLiuA());
            typeData.setSludgeReturnTwoA(operatingExcelData.getWuNiJiangChenErJiHuiLiuB());
        } else if ("剩余污泥量排放量".equals(type)) {
            typeData.setSstOneA(operatingExcelData.getShengYuWuNiYiJiErChenA());
            typeData.setSstOneB(operatingExcelData.getShengYuWuNiYiJiErChenB());
            typeData.setSstTwoA(operatingExcelData.getShengYuWuNiErJiErChenA());
            typeData.setSstTwoB(operatingExcelData.getShengYuWuNiErJiErChenB());
        }
        return typeData;
    }

    private TdOperatingParams buildMainData(OperatingExcelData operatingExcelData, Long projectId) throws ParseException {
        TdOperatingParams mainData = new TdOperatingParams();
        mainData.setProjectId(projectId);

        //校验日期和时间非空
        String date = operatingExcelData.getDate();
        String time = operatingExcelData.getTime();
        if (date == null || time == null) {
            throw new IllegalArgumentException("日期或时间不能为空");
        }
        // 合并日期时间字符串（格式：yyyy年M月d日 HH:mm）
        String dateTimeStr = date.trim() + " " + time.trim();

        // 解析为Date（仅保留必要格式，适配Excel实际格式）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm", Locale.CHINESE);
        sdf.setLenient(false); // 严格校验格式
        Date recordTime = sdf.parse(dateTimeStr);
        mainData.setRecordTime(recordTime);

        mainData.setEnable(null);
        mainData.setCreateTime(new Date());
        mainData.setUpdateTime(new Date());
        mainData.setCreateBy(SecurityUtils.getUsername());
        mainData.setUpdateBy(SecurityUtils.getUsername());

        return mainData;
    }
    private void validateDateContinuity(List<OperatingExcelData> dataList) {

        try {
            // 提取并解析所有日期
            List<Date> dateList = new ArrayList<>(dataList.size());
            for (OperatingExcelData data : dataList) {
                String dateStr = data.getDate();
                if (dateStr == null || dateStr.trim().isEmpty()) {
                    throw new IllegalArgumentException("第" + (dateList.size() + 1) + "行：日期不能为空");
                }
                // 解析日期字符串为Date（仅保留日期部分）
                Date date = DATE_FORMAT.parse(dateStr.trim());
                dateList.add(date);
            }

            // 校验连续日期
            for (int i = 1; i < dateList.size(); i++) {
                Date prevDate = dateList.get(i - 1);
                Date currDate = dateList.get(i);

                // 计算前一天日期
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(prevDate);
                calendar.add(Calendar.DAY_OF_YEAR, 1);
                Date expectedNextDate = calendar.getTime();

                // 比较当前日期是否为前一天的次日
                if (!currDate.equals(expectedNextDate)) {
                    // 格式化错误信息中的日期
                    String prevDateStr = DATE_FORMAT.format(prevDate);
                    String currDateStr = DATE_FORMAT.format(currDate);
                    throw new RuntimeException(
                            String.format("日期不连续：第%d行日期为%s，第%d行日期为%s（应为%s的次日）",
                                    i, prevDateStr, i + 1, currDateStr, prevDateStr)
                    );
                }
            }
        } catch (ParseException e) {
            throw new RuntimeException("日期格式错误：" + e.getMessage(), e);
        }
    }
}
